package cn.livingCloud.security;

import cn.livingCloud.context.Config;
import cn.livingCloud.context.SessionConstants;
import cn.livingCloud.service.SettingService;
import cn.livingCloud.wechat.config.WechatConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by 唐旭 on 2016/6/16.
 */
@Component
public class CustomCasFilter extends CasFilter {
    private static Logger logger = LoggerFactory.getLogger(CustomCasFilter.class);
    private String failureUrl = "/auto_login.htm?redirectUrl=%s";
    @Autowired
    private SettingService settingService;

    public CustomCasFilter() {
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = this.getSubject(request, response);
        Object attribute = subject.getSession().getAttribute(SessionConstants.MEMBER_KEY);
        return attribute != null;
    }

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String ticket = httpRequest.getParameter("code");
        return new CasToken(ticket);
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request, ServletResponse response) {
        Subject subject = this.getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            try {
                WebUtils.issueRedirect(request, response, buildRedirectUrl((HttpServletRequest) request));
            } catch (IOException var7) {
                logger.error("Cannot redirect to failure url : {}", buildRedirectUrl((HttpServletRequest) request), var7);
            }
        } else {
            try {
                this.issueSuccessRedirect(request, response);
            } catch (Exception var8) {
                logger.error("Cannot redirect to the default success url", var8);
            }
        }

        return false;
    }

    private String buildRedirectUrl(HttpServletRequest httpServletRequest) {
        String queryString = httpServletRequest.getQueryString();
        String requestURI = httpServletRequest.getRequestURI();
        if (StringUtils.isNotEmpty(queryString)) {
            requestURI = requestURI + "?" + queryString;
        }
        String format = String.format(failureUrl, requestURI);
        String url = Config.getDomainUrl() + format;
        return WechatConfig.getRedirectUserAuthorizeUrl(url, settingService.getAppid());
    }
}
